import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Banner from './Banner'
import SectionTitle from './SectionTitle'
import HouseCard, { type HouseItem } from './HouseCard'
import { fetchReceptionPage } from '../../services/api'
import styles from './index.module.css'
import { PullToRefresh, InfiniteScroll, Toast } from 'antd-mobile'
import placeholder from '../../assets/placeholder.png'

export default function Home() {
  const navigate = useNavigate()
  const pageRef = useRef(1)
  const pageSizeRef = useRef(10)
  const loadingRef = useRef(false)
  const [loaded, setLoaded] = useState(false)

  async function queryPage(reset = false) {
    if (loadingRef.current) return
    loadingRef.current = true
    const res = await fetchReceptionPage({
      current: pageRef.current,
      size: pageSizeRef.current,
    }).catch(() => null)
    if (res) {
      const list = (res.records || []).map((it: any) => toHouseItem(it))
      setData(prev => (reset ? list : [...prev, ...list]))
      const noMore = (res.current || 1) >= (res.pages || 1)
      setHasMore(!noMore)
      if (!noMore) pageRef.current += 1
    }
    loadingRef.current = false
    setLoaded(true)
  }

  useEffect(() => {
    queryPage(true)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  const bannerItems = useMemo(
    () => [
      { id: 1, image: 'https://picsum.photos/800/320?1', caption: '最新消息通知' },
      { id: 2, image: 'https://picsum.photos/800/320?2', caption: '社区公告：周末停水' },
    ],
    [],
  )
  const [data, setData] = useState<HouseItem[]>([])
  const [hasMore, setHasMore] = useState(true)

  async function loadMore() {
    await queryPage(false)
  }

  async function onRefresh() {
    pageRef.current = 1
    setHasMore(true)
    setData([])
    setLoaded(false)
    await queryPage(true)
    Toast.show('已刷新')
  }

  function toHouseItem(it: any): HouseItem {
    return {
      id: it.id,
      title: it.buildingEstateName || it.projectName || '—',
      buildingInfo: it.houseNo ? `-${it.houseNo}` : '',
      area: it.bedRoomNum ? `${it.bedRoomNum} 室` : '',
      time: it.receiveTime || '',
      contact: it.phone ? String(it.phone) : '—',
      price: typeof it.monthlyRent === 'number' ? String(it.monthlyRent) : '0',
    }
  }

  return (
    <div className={styles['home-page']}>
      <div className={styles['home-header']}>
        <div className={styles['home-banner']}>
          <Banner items={bannerItems} />
        </div>
        <SectionTitle>待办任务</SectionTitle>
      </div>
      <div className={styles['home-list-scroll']}>
        <PullToRefresh onRefresh={onRefresh}>
          {loaded && data.length === 0 ? (
            <div className={styles['empty-wrap']}>
              <img src={placeholder} alt="empty" className={styles['empty-image']} />
              <div className={styles['empty-text']}>暂无数据</div>
            </div>
          ) : (
            data.map(item => (
              <HouseCard key={item.id} item={item} onClick={id => navigate(`/acceptance/${id}`)} />
            ))
          )}
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </PullToRefresh>
      </div>
    </div>
  )
}
